package com.manong.config.handler;

import com.alibaba.fastjson.JSON;
import com.manong.config.security.exception.CustomerAuthenticationException;
import com.manong.utils.Result;
import com.manong.utils.ResultCode;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 李茂鑫
 * @Date 2025/1/13 15:02
 * @Descripition  登录失败处理器
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
//AuthenticationFailureHandler接口，负责在用户认证失败时执行自定义逻辑。
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        ServletOutputStream outputStream=response.getOutputStream();
        String  message =null;
        //定义对象，保存异常信息
        int code=500;
        // //instanceof是Java中的二元运算符，左边是对象，右边是类；当对象是右边类或子类所创建对象时，返回true；否则，返回false。
        if(exception instanceof AccountExpiredException){
            message="账户过期，登录失败";
        } else if (exception instanceof BadCredentialsException) {
            message="用户名或密码错误，登录失败";
        } else if (exception instanceof DisabledException) {
            message="账户被禁用，登录失败";
        } else if (exception instanceof LockedException) {
            message="账户被锁定，登录失败";
        } else if (exception instanceof InternalAuthenticationServiceException) {
            message="账户不存在，登陆失败";
        } else if (exception instanceof CustomerAuthenticationException) {
            message = exception.getMessage();
            code=600;

        } else {
            message="登陆失败";
        }
        //AccountExpiredException：账户过期。
        //BadCredentialsException：用户名或密码错误。
        //DisabledException：账户被禁用。
        //LockedException：账户被锁定。
        //InternalAuthenticationServiceException：账户不存在。
        String result= JSON.toJSONString(Result.error().code(ResultCode.ERROR).message(message));
        ////将结果转换为json格式返回
        outputStream.write(result.getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();

    }
}
